package com.sambo.inspection.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.google.gson.JsonElement;
import com.sambo.inspection.InspectionApplication;
import com.sambo.inspection.R;
import com.sambo.inspection.activity.support.BaseActivity;
import com.sambo.inspection.bean.CheckPointStateBean;
import com.sambo.inspection.bean.GlobleBean;
import com.sambo.inspection.bean.InspectionBean;
import com.sambo.inspection.bean.InspectionPointBean;
import com.sambo.inspection.bean.InspectionStateBean;
import com.sambo.inspection.bean.TrajectoryBean;
import com.sambo.inspection.component.ZnkConfirmDialog;
import com.sambo.inspection.component.ZnkProgressDialog;
import com.sambo.inspection.http.HttpClient;
import com.sambo.inspection.http.HttpResponseHandler;
import com.sambo.inspection.http.Urls;
import com.sambo.inspection.map.overlay.DrivingRouteOverlay;
import com.sambo.inspection.util.JsonUtil;
import com.sambo.inspection.util.LogUtil;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RoutingInspectionDetailActivity extends BaseActivity
        implements View.OnClickListener, AMap.OnMarkerClickListener, AMap.OnInfoWindowClickListener, RouteSearch.OnRouteSearchListener {

    ImageView ivBack;
    TextView tvTitle;
    MapView mapView;
    ImageView ivLocation;
    TextView tvStartInspection;

    private AMap aMap;
    private UiSettings uiSettings;

    private CameraUpdate mUpdate;
    //途经点集合
    private ArrayList<InspectionPointBean> list;
    private ArrayList<LatLonPoint> list1;
    private Map<String, InspectionPointBean> markerPointMap;

    private DriveRouteResult driveRouteResult;// 驾车模式查询结果

    private int drivingMode = RouteSearch.DRIVING_MULTI_STRATEGY_FASTEST_SHORTEST;// 驾车默认模式

    private RouteSearch routeSearch;
    private RouteSearch inspectionSearch;

    private InspectionBean mInspectionBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_routing_inspection_detail);

        ivBack = findViewById(R.id.iv_back);
        tvTitle = findViewById(R.id.tv_title);
        ivLocation = findViewById(R.id.iv_location);
        tvStartInspection = findViewById(R.id.tv_start_inspection);
        mapView = findViewById(R.id.map);
        mapView.onCreate(savedInstanceState); // 此方法必须重写

        list = new ArrayList<>();
        list1 = new ArrayList<>();
        markerPointMap = new HashMap<>();

        initMap();

        ivBack.setOnClickListener(this);
        ivLocation.setOnClickListener(this);
        tvStartInspection.setOnClickListener(this);

        mInspectionBean = (InspectionBean) getIntent().getSerializableExtra("model");
        tvTitle.setText(getIntent().getStringExtra("title"));

        if (!TextUtils.isEmpty(mInspectionBean.getRoute_planning_id())) {
            // 获取检查点信息
            getCheckPointInfo();

            if (TextUtils.equals("1", mInspectionBean.getState())) {
                tvStartInspection.setText("开始巡检");
                tvStartInspection.setBackgroundColor(getResources().getColor(R.color.weixin_green));
            } else if (TextUtils.equals("2", mInspectionBean.getState())) {
                tvStartInspection.setText("巡检完成");
                tvStartInspection.setBackgroundColor(getResources().getColor(R.color.orange));
                InspectionApplication.getInstance().startUploadLocation(mInspectionBean.getId());
            } else {
                tvStartInspection.setVisibility(View.INVISIBLE);
                getTrajectory();
            }
        } else {
            tvStartInspection.setVisibility(View.INVISIBLE);
            Toast.makeText(RoutingInspectionDetailActivity.this, "未获取到检查点信息", Toast.LENGTH_LONG).show();
        }

    }

    private void initMap() {

        if (aMap == null) {
            aMap = mapView.getMap();
        }

        uiSettings = aMap.getUiSettings();
        uiSettings.setZoomControlsEnabled(false);

        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 在地图上添加marker
     */
    private void drawMarkers() {

        String[] location;

        markerPointMap.clear();

        for (int i = 0; i < list.size(); i++) {
            location = list.get(i).getLocation().split(",");
            if (location.length == 2) {
                View view = View.inflate(this, R.layout.custom_info_window, null);
                TextView mark_id = (TextView) view.findViewById(R.id.title);
                mark_id.setText((i + 1) + "");
                Bitmap bitmap = convertViewToBitmap(view);
                //窗口信息
                drawMarkerOnMap(new LatLng(Double.parseDouble(location[1]), Double.parseDouble(location[0])), bitmap, list.get(i));
            }
        }

    }

    public static Bitmap convertViewToBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        return view.getDrawingCache();
    }

    private Marker drawMarkerOnMap(LatLng point, Bitmap markerIcon, InspectionPointBean mapInfo) {
        if (aMap != null && point != null) {
            Marker marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 1)
                    .position(point)
                    .title(mapInfo.getName())
                    .snippet(mapInfo.getDescription())
                    .icon(BitmapDescriptorFactory.fromBitmap(markerIcon)));
            markerPointMap.put(marker.getId(), mapInfo);

            return marker;
        }
        return null;
    }

    /**
     * 对marker标注点点击响应事件
     */
    @Override
    public boolean onMarkerClick(final Marker marker) {
        marker.showInfoWindow();
        return false;
    }

    /**
     * 监听点击infowindow窗口事件回调
     */
    @Override
    public void onInfoWindowClick(final Marker marker) {

        if (TextUtils.equals("2", mInspectionBean.getState())) {
            ZnkConfirmDialog dialog = ZnkConfirmDialog.createDialog(this, "上报当前检查点的状态", "正常", "故障",
                    new ZnkConfirmDialog.OnClickCallBack() {
                        @Override
                        public void exec() {
                            updateCheckPointState(markerPointMap.get(marker.getId()).getCode(), "1");
                        }
                    }, new ZnkConfirmDialog.OnClickCallBack() {
                        @Override
                        public void exec() {
                            updateCheckPointState(markerPointMap.get(marker.getId()).getCode(), "2");
                        }
                    });

            dialog.show();
        }

    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
        if (rCode == 1000) {
            if (result != null && result.getPaths() != null
                    && result.getPaths().size() > 0) {
                driveRouteResult = result;
                DrivePath drivePath = driveRouteResult.getPaths().get(0);

                RouteTool routeTool = new RouteTool(this, aMap, drivePath, driveRouteResult.getStartPos(), driveRouteResult.getTargetPos(), list1);
                routeTool.setView(Color.BLUE, 16);
                routeTool.removeFromMap();
                routeTool.addToMap();
                routeTool.zoomToSpan();

            } else {

                Toast.makeText(this, "对不起，没有搜索到相关数据！", Toast.LENGTH_SHORT).show();
            }
        } else if (rCode == 27) {

            Toast.makeText(this, "搜索失败,请检查网络连接！", Toast.LENGTH_SHORT).show();
        } else if (rCode == 32) {

            Toast.makeText(this, "key验证无效！", Toast.LENGTH_SHORT).show();
        } else {

            Toast.makeText(this, "未知错误，请稍后重试!错误码为" + rCode, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_location:
                returnCurrentPotion();
                break;
            case R.id.tv_start_inspection:
                try {
                    int state = Integer.parseInt(mInspectionBean.getState());
                    final String updateState = String.valueOf(++state);

                    if (state == 3) {
//                        String unCheckPointContent = checkUpload();
//                        if (!TextUtils.isEmpty(unCheckPointContent)) {
//                            Dialog dialog = ZnkConfirmDialog.createDialog(this, String.format("当前巡检任务未上报%s状态，任务无法结束", unCheckPointContent),
//                                    null, null);
//                            dialog.show();
//                            return;
//                        }

                        Dialog dialog = ZnkConfirmDialog.createDialog(this, "确定要结束巡检任务吗？",
                                new ZnkConfirmDialog.OnClickCallBack() {
                                    @Override
                                    public void exec() {
                                        updateInspectionState(updateState);
                                    }
                                }, null);

                        dialog.show();
                    } else {
                        updateInspectionState(updateState);
                    }
                } catch (NumberFormatException e) {
                    LogUtil.e("修改巡检状态失败！state=" + mInspectionBean.getState());
                }
                break;
        }
    }

    private void getCheckPointInfo() {

        final ZnkProgressDialog dialog = ZnkProgressDialog.createLoadingDialog(this, "加载中...");
        dialog.show();

        Map<String, String> params = new HashMap<>();

        params.put("planTrackId", mInspectionBean.getRoute_planning_id());

        HttpClient.get(this, Urls.API_SERVER_HOST + Urls.GET_TASK_CHECK_POINT, params,
                new HttpResponseHandler() {

                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);
                        list.clear();

                        InspectionPointBean[] response = JsonUtil.toObj(value.toString(), InspectionPointBean[].class);

                        if (response != null && response.length > 0) {
                            list.addAll(Arrays.asList(response));
                            setLocationInfo();
                        } else {
                            tvStartInspection.setVisibility(View.INVISIBLE);
                            Toast.makeText(RoutingInspectionDetailActivity.this, "未获取到检查点信息", Toast.LENGTH_LONG).show();
                        }

                    }

                    @Override
                    public void onInnovationFinish() {
                        super.onInnovationFinish();
                        dialog.dismiss();
                    }
                }, new HttpClient.NetworkUnavailableListener() {
                    @Override
                    public void networkUnavailable() {
                        dialog.dismiss();
                    }
                });
    }

    private void getTrajectory() {

        Map<String, String> params = new HashMap<>();

        params.put("messionId", String.valueOf(mInspectionBean.getId()));

        HttpClient.get(this, Urls.API_SERVER_HOST + Urls.GET_TRAJECTORY, params,
                new HttpResponseHandler() {

                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);

                        TrajectoryBean response = JsonUtil.toObj(value.toString(), TrajectoryBean.class);

                        if (response != null) {
                            List<List<Double>> pointList = response.getMarkerData();

                            if (pointList != null && pointList.size() > 0) {
                                showTrajectory(pointList);

                            } else {
                                Toast.makeText(RoutingInspectionDetailActivity.this, "未获取到巡检轨迹信息", Toast.LENGTH_LONG).show();
                            }
                        }

                    }

                }, null);
    }

    private void showTrajectory(List<List<Double>> pointList) {
        drawTrajectory(pointList);

        if (pointList.size() > 1) {
            inspectionSearch = new RouteSearch(this);
            inspectionSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
                @Override
                public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

                }

                @Override
                public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int rCode) {
                    if (rCode == 1000) {
                        if (driveRouteResult != null && driveRouteResult.getPaths() != null
                                && driveRouteResult.getPaths().size() > 0) {
                            DrivePath drivePath = driveRouteResult.getPaths().get(0);

                            RouteTool routeTool = new RouteTool(RoutingInspectionDetailActivity.this, aMap, drivePath, driveRouteResult.getStartPos(), driveRouteResult.getTargetPos(), list1);
                            routeTool.setView(Color.BLUE, 16);
                            routeTool.removeFromMap();
                            routeTool.addToMap();

                        } else {

                            Toast.makeText(RoutingInspectionDetailActivity.this, "对不起，没有搜索到相关数据！", Toast.LENGTH_SHORT).show();
                        }
                    } else if (rCode == 27) {

                        Toast.makeText(RoutingInspectionDetailActivity.this, "搜索失败,请检查网络连接！", Toast.LENGTH_SHORT).show();
                    } else if (rCode == 32) {

                        Toast.makeText(RoutingInspectionDetailActivity.this, "key验证无效！", Toast.LENGTH_SHORT).show();
                    } else {

                        Toast.makeText(RoutingInspectionDetailActivity.this, "未知错误，请稍后重试!错误码为" + rCode, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

                }

                @Override
                public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

                }
            });

            List<LatLonPoint> inspectionPointList = new ArrayList<>();

            for (List<Double> point : pointList) {
                inspectionPointList.add(new LatLonPoint(point.get(1), point.get(0)));
            }

            // 设置起点和终点
            final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(inspectionPointList.get(0), inspectionPointList.get(inspectionPointList.size() - 1));
            // 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, drivingMode, inspectionPointList, null, "");
            // 异步路径规划驾车模式查询
            inspectionSearch.calculateDriveRouteAsyn(query);
        }

    }

    private void updateInspectionState(final String state) {

        final ZnkProgressDialog dialog = ZnkProgressDialog.createLoadingDialog(this, "加载中...");
        dialog.show();

        InspectionStateBean bean = new InspectionStateBean();
        bean.setMessionId(mInspectionBean.getId());
        bean.setState(state);
        bean.setCreatedBy(GlobleBean.getInstance().getUserName());

        HttpClient.post(this, Urls.API_SERVER_HOST + Urls.UPDATE_INSPECTION_STATE, bean,
                new HttpResponseHandler() {

                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);
                        dialog.dismiss();
                        mInspectionBean.setState(state);
                        if (TextUtils.equals("2", mInspectionBean.getState())) {
                            InspectionApplication.getInstance().startUploadLocation(mInspectionBean.getId());
                            tvStartInspection.setText("巡检完成");
                            tvStartInspection.setBackgroundColor(getResources().getColor(R.color.orange));
                        } else if (TextUtils.equals("3", mInspectionBean.getState())) {
                            InspectionApplication.getInstance().stopUploadLocation();
                            tvStartInspection.setVisibility(View.INVISIBLE);
                            finish();
                        }
                    }

                    @Override
                    public void onInnovationFailure(String msg) {
                        super.onInnovationFailure(msg);
                        dialog.dismiss();
                    }
                }, new HttpClient.NetworkUnavailableListener() {
                    @Override
                    public void networkUnavailable() {
                        dialog.dismiss();
                    }
                });
    }

    private void updateCheckPointState(String checkPointID, final String state) {

        final ZnkProgressDialog dialog = ZnkProgressDialog.createLoadingDialog(this, "上报中...");
        dialog.show();

        CheckPointStateBean bean = new CheckPointStateBean();
        bean.setCheckPointId(checkPointID);
        bean.setState(state);
        bean.setCreatedBy(GlobleBean.getInstance().getUserName());

        HttpClient.post(this, Urls.API_SERVER_HOST + Urls.UPDATE_CHECK_POINT_STATE, bean,
                new HttpResponseHandler() {

                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);
                        Toast.makeText(RoutingInspectionDetailActivity.this, "上报检查点状态成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onInnovationFinish() {
                        super.onInnovationFinish();
                        dialog.dismiss();
                    }
                }, new HttpClient.NetworkUnavailableListener() {
                    @Override
                    public void networkUnavailable() {
                        dialog.dismiss();
                    }
                });
    }

    private void setLocationInfo() {
        // 这是地理位置（经纬度）
        String[] location;
        for (int i = 0; i < list.size(); i++) {
            location = list.get(i).getLocation().split(",");
            list1.add(new LatLonPoint(Double.parseDouble(location[1]), Double.parseDouble(location[0])));
            mUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                    new LatLng(Double.parseDouble(location[1]), Double.parseDouble(location[0])), 16, 0, 30));
            // 定位的方法
            aMap.moveCamera(mUpdate);
        }

        drawMarkers();// 往地图上添加marker

        routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(this);
        // 设置起点和终点
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(list1.get(0), list1.get(list1.size() - 1));
        // 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, drivingMode, list1, null, "");
        // 异步路径规划驾车模式查询
        routeSearch.calculateDriveRouteAsyn(query);
    }

    /**
     * 回到当前位置
     */
    private void returnCurrentPotion() {
        AMapLocation location = InspectionApplication.getInstance().getLastLocation();
        if (location != null) {
            CameraUpdate update = CameraUpdateFactory.newCameraPosition(new CameraPosition(
                    new LatLng(location.getLatitude(), location.getLongitude()), 16, 0, 30));
            // 定位的方法
            aMap.moveCamera(update);

        }
    }

    private void drawTrajectory(List<List<Double>> pointList) {
        for (List<Double> latlng : pointList) {
            aMap.addMarker(new MarkerOptions().anchor(0.5f, 1)
                    .position(new LatLng(latlng.get(1), latlng.get(0)))
                    .icon(BitmapDescriptorFactory.defaultMarker()));
        }
    }

    /**
     * 自定义路线的颜色、宽度、小汽车标志
     */
    class RouteTool extends DrivingRouteOverlay {
        int color;//路线颜色
        float lineWidth;//路线宽度

        // 修改路线宽度
        @Override
        public float getRouteWidth() {
            return lineWidth;
        }

        // 修改路线颜色
        @Override
        protected int getDriveColor() {
            return color;
        }

        public RouteTool(Context context, AMap aMap, DrivePath drivePath, LatLonPoint latLonPoint, LatLonPoint latLonPoint1, List<LatLonPoint> throughPointList) {
            super(context, aMap, drivePath, latLonPoint, latLonPoint1, throughPointList);
        }

        /*修改起点marker样式*/
        @Override
        protected BitmapDescriptor getStartBitmapDescriptor() {
            BitmapDescriptor reBitmapDescriptor = new BitmapDescriptorFactory().fromResource(R.mipmap.transparent);

            return reBitmapDescriptor;
        }

        /*修改中间点marker样式*/
        @Override
        protected BitmapDescriptor getDriveBitmapDescriptor() {
            BitmapDescriptor reBitmapDescriptor = new BitmapDescriptorFactory().fromResource(R.mipmap.transparent);

            return reBitmapDescriptor;
        }

        /*修改终点marker样式*/
        @Override
        protected BitmapDescriptor getEndBitmapDescriptor() {
            BitmapDescriptor reBitmapDescriptor = new BitmapDescriptorFactory().fromResource(R.mipmap.transparent);
            return reBitmapDescriptor;
        }

        /*修改途径点marker样式*/
        @Override
        protected BitmapDescriptor getThroughPointBitDes() {
            return BitmapDescriptorFactory.fromResource(R.mipmap.transparent);
//       return BitmapDescriptorFactory.defaultMarker();
        }

        // 一个工具方法，修改颜色和宽度
        public void setView(int color, float width) {
            this.color = color;
            this.lineWidth = width;
        }
    }

}
